package com.jpa.order.controller;

import com.jpa.order.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author: MR.LIU
 * @description:
 * @date: 2020/5/30
 * @time: 15:57
 */
@RestController
@RequestMapping(value = "/order")
public class OrderController {
    @Autowired
    private RestTemplate restTemplate;

    /**
     * spring cloud 提供获取eureka-server服务元数据的工具类
     */
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping(value = "/buy/{id}")
    public Product findProductById(@PathVariable Long id) {
        Product product = restTemplate.getForObject("http://localhost:9001/product/byId/" + id, Product.class);
        return product;
    }

    @GetMapping(value = "/by/{id}")
    public Product findProduct(@PathVariable Long id) {
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance serviceInstance = instances.get(0);
        Product product = restTemplate.getForObject("http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/product/byId/" + id, Product.class);
        return product;
    }
}
